<template>
    <div class='role'>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-button type="success" plain @click='showadddialog'>添加角色</el-button>
        <!-- 表格--展开行 -->
        <template>
            <el-table :data="rolesList" style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                       <el-row v-for='first in scope.row.children' :key='first.id' style='margin-bottom:15px'>
                         <el-col :span='4'>
                           <el-tag
                            closable
                            type="success"
                            @close='deleteroleright(scope.row,first.id)'>
                            {{first.authName}}
                          </el-tag>
                          <span class='el-icon-arrow-right' v-if='first.children.length !==0'></span>
                         </el-col>
                         <el-col :span='20'>
                           <el-row v-for='second in first.children' :key='second.id' style='margin-bottom:6px'>
                             <el-col :span='4'>
                                <el-tag
                                closable
                                type="info"
                                 @close='deleteroleright(scope.row,second.id)'>
                                {{second.authName}}
                                </el-tag>
                                <span class='el-icon-arrow-right' v-if='second.children.length !==0'></span>
                             </el-col>
                             <el-col :span='20'>
                               <el-tag
                               v-for='third in second.children' :key='third.id'
                               style='margin-left:6px;margin.top:6px'
                                closable
                                type="danger"
                                 @close='deleteroleright(scope.row,third.id)'>
                                {{third.authName}}
                                </el-tag>
                             </el-col>
                           </el-row>
                         </el-col>
                       </el-row>
                       <span v-if='scope.row.children.length === 0'>该角色还没有分配任何权限</span>
                    </template>
                </el-table-column>
                <el-table-column label="角色名称" prop="roleName">
                </el-table-column>
                <el-table-column label="描述" prop="roleDesc">
                </el-table-column>
                <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- plain:属性来定义 Button 的样式。 -->
                    <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                    <el-button type="primary" icon="el-icon-edit" plain @click='showEditDialog(scope.row)'></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                    <el-button type="primary" icon="el-icon-delete" plain @click='showDelDialog(scope.row.id)'></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="授权角色" placement="top-start">
                    <el-button type="primary" icon="el-icon-check" plain  @click='showGrantDialog(scope.row)'></el-button>
                    </el-tooltip>
                </template>
                </el-table-column>
            </el-table>
        </template>
        <!-- 对话框 -->
        <el-dialog title="分配权限" :visible.sync="grantDialogFormVisible">
          <div class="treeBox">
              <el-tree
              ref='tree'
              :data="rightsList"
              show-checkbox
              node-key="id"
              :default-expand-all='true'
              :default-checked-keys="rolederightlist"
              :props="defaultProps">
              </el-tree>
          </div>
          <div slot="footer" class="dialog-footer">
              <el-button @click="grantDialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click='grantrightsubmit'>确 定</el-button>
          </div>
        </el-dialog>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加角色" :visible.sync="adddialogFormVisible">
          <el-form :model="addform" label-width="100px" ref='addform'>
            <el-form-item label="角色名称:">
              <el-input v-model="addform.roleName" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述:">
              <el-input v-model="addform.roleDesc" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="adddialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUserSubmit('addform')">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 编辑用户信息的对话框 -->
        <el-dialog title="添加角色" :visible.sync="editdialogFormVisible">
          <el-form :model="editform" label-width="100px" ref='editform'>
            <el-form-item label="角色名称:">
              <el-input v-model="editform.roleName" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述:">
              <el-input v-model="editform.roleDesc" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="editdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserSubmit('editform')">确 定</el-button>
          </div>
        </el-dialog>
    </div>
</template>
<script>
import {getRolesList, getRightList, grantroleright, addRole, deleteroleright, deleterole, editroles} from '@/api/index.js'
export default {
  data () {
    return {
      grantDialogFormVisible: false,
      adddialogFormVisible: false,
      editdialogFormVisible: false,
      rolesList: [],
      defaultProps: {
        //   指定子树为节点对象的某个属性值
        children: 'children',
        // 指定节点标签为节点对象的某个属性值
        label: 'authName'
      },
      rightsList: [],
      // 在data中添加数据成员
      rolederightlist: [],
      //   当前角色的id
      currentRoleId: '',
      addform: {
        roleName: '',
        roleDesc: ''
      },
      editform: {
        roleName: '',
        roleDesc: '',
        id: ''
      }
    }
  },
  methods: {
    // 0.初始化
    initList () {
      // 使用获取角色列表的接口:获取所有角色列表数据
      getRolesList()
        .then((res) => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.rolesList = res.data
          }
        })
    },
    //  1. 打开分配角色对话框
    showGrantDialog (row) {
      // console.log('-------')
      // console.log(row)
      // console.log('-------')
      // 显示分配权限对话框
      this.currentRoleId = row.id
      this.grantDialogFormVisible = true
      // 获取数据，将数据展示在树形组件中   tree 树状显示权限
      getRightList({type: 'tree'})
        .then((res) => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.rightsList = res.data
          }
        })
        // id值叠加的解决方法:在每次点击遍历数据的时候先清除上一次的id值
      this.rolederightlist.length = 0
      // 打开对话框的时候去获取当前角色的权限列表id,因为每个角色的权限都可能不一样,所以每次弹框都需要重新获取这个列表id
      // 遍历row.children里面的数据
      row.children.forEach((first, index) => {
        // console.log(index)
        // 判断是否有first.children 和 first.children的索引不等于0
        if (first.children && first.children.length !== 0) {
          // 继续遍历first.children里面的数据
          first.children.forEach((second) => {
            // console.log(second)
            if (second.children && second.children.length !== 0) {
              // 再次循环second.children里面的数据
              second.children.forEach((third) => {
                // console.log(third)
                this.rolederightlist.push(third.id)
              })
            }
          })
        }
      })
      // 这是打印this.rolederightlist数据的时候,每次点击授权角色的索引值都会叠加起来,因为上一次点击后的id值没有删除掉,所以点击其他的角色的时候id值会叠加起来
      // console.log(this.rolederightlist)
    },
    // 2.当前角色的选择授权提交
    grantrightsubmit () {
      // console.log(this.currentRoleId)
      // console.log(this.$refs.tree.getCheckedKeys())
      // 选择使用this.$refs.tree.getCheckedNodes()
      // console.log(this.$refs.tree.getCheckedNodes())
      // 1.获取当前所有被选中的节点对象.他是一个数组
      var selectednodes = this.$refs.tree.getCheckedNodes()
      // console.log(selectednodes)

      // 2.遍历数组,获取我们需要的每一个对象中的id和pid
      var originArr = selectednodes.map((item) => {
        return item.id + ',' + item.pid
      })
      // console.log(originArr) // ["105,104,101", "116,104,101"]

      // 3.将获取到的数据拼接成一个整体的字符串  -- 当然会有重复值
      var originStr = originArr.join(',')
      // console.log(originStr)

      // 4.使用new Set去除重复值并且会返回一个新的set对象
      // split() 方法用于把一个字符串分割成字符串数组。
      var myset = new Set(originStr.split(','))
      // console.log(myset)

      // 5.使用Array.from从set对象返回数组
      var finalArr = Array.from(myset)
      // console.log(finalArr)
      grantroleright(this.currentRoleId, {rids: finalArr.join(',')})
        .then((res) => {
          // console.log(res)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            // 分配权限完成后关机对话框
            this.grantDialogFormVisible = false
            this.initList()
            // 自动的刷新角色分配
            this.initList()
          } else {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
          }
        })
    },
    // 3.显示添加用户的对话框
    showadddialog () {
      this.adddialogFormVisible = true
    },
    // 4.添加用户的功能
    addUserSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addRole(this.addform)
            .then((res) => {
              console.log(res)
              if (res.meta.status === 201) {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                this.adddialogFormVisible = false
                this.initList()
              } else {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
              }
            })
        } else {
          this.$message({
            type: 'success',
            message: '输入不合法,请重新输入'
          })
        }
      })
    },
    // 5.删除角色的权限
    deleteroleright (row, rightid) {
      deleteroleright(row.id, rightid)
        .then((res) => {
          console.log(res)
          if (res.meta.status === 200) {
            this.$message({
              type: 'success',
              message: res.meta.msg
            })
            // this.initList()
            row.children = res.data
          } else {
            this.$message({
              type: 'danger',
              message: res.meta.msg
            })
          }
        })
    },
    // 6.删除角色的整体数据
    showDelDialog (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleterole(id)
            .then((res) => {
              console.log(res)
              if (res.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                this.initList()
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 7.显示编辑对话框
    showEditDialog (row) {
      this.editdialogFormVisible = true
      console.log(row)
      this.editform.roleName = row.roleName
      this.editform.roleDesc = row.roleDesc
      this.editform.id = row.id
    },
    // 8.实现编辑用户的功能
    editUserSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          editroles(this.editform)
            .then((res) => {
              console.log(res)
              if (res.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
                this.initList()
                this.editdialogFormVisible = false
              } else {
                this.$message({
                  type: 'success',
                  message: res.meta.msg
                })
              }
            })
        }
      })
    }
  },
  mounted () {
    this.initList()
  }

}
</script>
<style lang="scss" scoped>
.treeBox{
    height: 300px;
    overflow: auto;
}
</style>
